package com.dwa.persistent;

import javax.sql.DataSource;

import org.apache.log4j.Logger;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;

/**
 * @author Vedamoorthi Vairam
 * @since 09/02/2009
 */
public abstract class AbstractDao implements IAbstractDao {

	private static final Logger logger = Logger.getLogger(AbstractDao.class);
	private String tableName;
	private String clazz;
	private RowMapper rowMapper;

	private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
	
	private JdbcTemplate jdbcTemplate;

	public void setDataSource(DataSource dataSource) {
		this.namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(
				dataSource);
		this.jdbcTemplate = new JdbcTemplate(dataSource);
	}

	public void create(Object obj) {
		// TODO Auto-generated method stub

	}

	public void delete(Object obj) {
		// TODO Auto-generated method stub

	}

	public Object edit(Object obj) {
		// TODO Auto-generated method stub
		return null;
	}

	public Object findById(Long id) {
		String query = "SELECT * FROM  " + getTableName() + " WHERE ID=:ID";
		logger.debug("Query " + query);
		logger.debug("Target " + getTargetClass().getSimpleName());
		SqlParameterSource namedParameters = new MapSqlParameterSource("ID", id);
		Object obj = namedParameterJdbcTemplate.queryForObject(query, namedParameters, getRowMapper());
		logger.debug("obj "   + obj);
		return obj;
	}

	private Class getTargetClass() {
		try {
			return Class.forName(getClazz()).getClass();
		} catch (ClassNotFoundException e) {
			logger.error("The specifed class not found : " + clazz);
			throw new RuntimeException("Class not found" + getClazz());
		}
	}

	public String getClazz() {
		return clazz;
	}

	public String getTableName() {
		return tableName;
	}

	public void setTableName(String tableName) {
		this.tableName = tableName;
	}

	public void setClazz(String clazz) {
		this.clazz = clazz;
	}

	public RowMapper getRowMapper() {
		return rowMapper;
	}

	public void setRowMapper(RowMapper rowMapper) {
		this.rowMapper = rowMapper;
	}

	public NamedParameterJdbcTemplate getNamedParameterJdbcTemplate() {
		return namedParameterJdbcTemplate;
	}
	
	public JdbcTemplate getJdbcTemplate() {
		return jdbcTemplate;
	}
}